<template>
	<view class="order-confirm">
		<view class="header">
			<view class="back-btn" @click="goBack">
				<u-icon name="arrow-left" size="24"></u-icon>
			</view>
			<text class="title">确认订单</text>
		</view>
		
		<view class="content">
			<!-- 景点信息 -->
			<view class="scenic-info" v-if="scenic">
				<image :src="scenic.coverImage" class="scenic-icon"></image>
				<view class="scenic-details">
					<text class="scenic-name">{{ scenic.title }}</text>
					<text class="scenic-address">{{ scenic.address }}</text>
				</view>
			</view>
			
			<!-- 门票信息 -->
			<view class="ticket-info" v-if="ticket">
				<view class="info-row">
					<text class="label">门票类型</text>
					<text class="value">{{ ticket.name }}</text>
				</view>
				<view class="info-row">
					<text class="label">数量</text>
					<view class="counter">
						<u-icon name="minus-circle" size="24" @click="decreaseCount"></u-icon>
						<text class="count">{{ count }}</text>
						<u-icon name="plus-circle" size="24" @click="increaseCount"></u-icon>
					</view>
				</view>
				<view class="info-row">
					<text class="label">单价</text>
					<text class="price">¥{{ ticket.price }}</text>
				</view>
			</view>
			
			<!-- 优惠券选择 -->
			<view class="coupon-section" @click="selectCoupon">
				<text class="label">优惠券</text>
				<view class="coupon-value">
					<text v-if="selectedCoupon">-¥{{ selectedCoupon.discountValue }}</text>
					<text v-else class="placeholder">{{ coupons.length }}张可用</text>
					<u-icon name="arrow-right" size="16"></u-icon>
				</view>
			</view>
			
			<!-- 支付方式选择 -->
			<view class="payment-section">
				<text class="section-title">支付方式</text>
				<view class="payment-methods">
					<view 
						class="payment-item" 
						:class="{selected: paymentMethod === 'wechat'}"
						@click="selectPaymentMethod('wechat')"
					>
						<view class="payment-icon wechat-icon">
							<u-icon name="weixin-fill" color="#07C160" size="40"></u-icon>
						</view>
						<text class="payment-name">微信支付</text>
						<u-icon v-if="paymentMethod === 'wechat'" name="checkbox-mark" color="#07C160" size="24"></u-icon>
					</view>
					<view 
						class="payment-item" 
						:class="{selected: paymentMethod === 'alipay'}"
						@click="selectPaymentMethod('alipay')"
					>
						<view class="payment-icon alipay-icon">
							<u-icon name="zhifubao" color="#1677FF" size="40"></u-icon>
						</view>
						<text class="payment-name">支付宝</text>
						<u-icon v-if="paymentMethod === 'alipay'" name="checkbox-mark" color="#1677FF" size="24"></u-icon>
					</view>
				</view>
			</view>
			
			<!-- 总价 -->
			<view class="total-section">
				<view class="total-row">
					<text class="label">小计</text>
					<text class="price">¥{{ subtotal }}</text>
				</view>
				<view class="total-row" v-if="selectedCoupon">
					<text class="label">优惠</text>
					<text class="discount">-¥{{ selectedCoupon.discountValue }}</text>
				</view>
				<view class="total-row final">
					<text class="label">实付</text>
					<text class="total-price">¥{{ totalPrice }}</text>
				</view>
			</view>
		</view>
		
		<!-- 底部按钮 -->
		<view class="footer">
			<view class="price-info">
				<text class="label">合计</text>
				<text class="total">¥{{ totalPrice }}</text>
			</view>
			<view class="pay-btn" @click="payOrder">
				<text>立即支付</text>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			scenicId: null,
			ticketId: null,
			scenic: null,
			ticket: null,
			count: 1,
			coupons: [],
			selectedCoupon: null,
			userId: null,
			paymentMethod: 'wechat' // 默认微信支付
		};
	},
	
	computed: {
		subtotal() {
			return (this.ticket?.price || 0) * this.count;
		},
		
		totalPrice() {
			let total = this.subtotal;
			if (this.selectedCoupon) {
				total -= this.selectedCoupon.discountValue;
			}
			return Math.max(0, total);
		}
	},
	
	onLoad(options) {
		if (options.scenicId) {
			this.scenicId = options.scenicId;
		}
		if (options.ticketId) {
			this.ticketId = options.ticketId;
		}
		
		// 获取用户ID
		const userInfo = uni.getStorageSync('userInfo') || uni.getStorageSync('user');
		if (userInfo && userInfo.id) {
			this.userId = userInfo.id;
		}
		
		this.loadData();
	},
	
	
	methods: {
		async loadData() {
			await Promise.all([
				this.loadScenicInfo(),
				this.loadTicketInfo(),
				this.loadCoupons()
			]);
		},
		
		async loadScenicInfo() {
			try {
				const res = await this.$api.getScenicDetail({
					id: this.scenicId
				});
				if (res.data && res.data.code === 200) {
					this.scenic = res.data.data;
				}
			} catch (error) {
				console.error('加载景点信息失败', error);
			}
		},
		
		async loadTicketInfo() {
			try {
				const res = await this.$api.getTicketDetail({
					id: this.ticketId
				});
				if (res.data && res.data.code === 200) {
					this.ticket = res.data.data;
				}
			} catch (error) {
				console.error('加载门票信息失败', error);
			}
		},
		
		async loadCoupons() {
			if (!this.userId) return;
			
			try {
				const res = await this.$api.getUserCoupons({
					userId: this.userId,
					status: 1
				});
				if (res.data && res.data.code === 200) {
					this.coupons = res.data.data || [];
				}
			} catch (error) {
				console.error('加载优惠券失败', error);
				this.coupons = [];
			}
		},
		
		increaseCount() {
			this.count++;
		},
		
		decreaseCount() {
			if (this.count > 1) {
				this.count--;
			}
		},
		
		selectPaymentMethod(method) {
			this.paymentMethod = method;
		},
		
		selectCoupon() {
			if (this.coupons.length === 0) {
				uni.showToast({
					title: '暂无可用优惠券',
					icon: 'none'
				});
				return;
			}
			
			// TODO: 跳转到优惠券选择页面
			uni.showModal({
				title: '选择优惠券',
				content: `您有${this.coupons.length}张可用优惠券`,
				success: (res) => {
					if (res.confirm && this.coupons.length > 0) {
						this.selectedCoupon = this.coupons[0];
					}
				}
			});
		},
		
		async payOrder() {
			if (!this.userId) {
				uni.showToast({
					title: '请先登录',
					icon: 'none'
				});
				return;
			}
			
			uni.showLoading({
				title: '创建订单中...'
			});
			
			try {
				// 创建订单
				const res = await this.$api.createOrder({
					userId: this.userId,
					scenicId: this.scenicId,
					ticketId: this.ticketId,
					count: this.count,
					couponId: this.selectedCoupon?.id || null,
					totalAmount: this.totalPrice
				});
				
				uni.hideLoading();
				
				if (res.data && res.data.code === 200) {
					// 订单创建成功，跳转到待付款列表
					uni.showToast({
						title: '订单创建成功',
						icon: 'success',
						duration: 1500
					});
					
					setTimeout(() => {
						// 跳转到"我的"页面的待付款订单列表
						uni.switchTab({
							url: '/pages/mine/mine',
							success: () => {
								// 使用uni.$emit发送事件，通知mine页面切换到待付款
								uni.$emit('switchToOrder', { status: 0 });
							}
						});
					}, 1500);
				} else {
					uni.showToast({
						title: res.data.message || '创建订单失败',
						icon: 'none'
					});
				}
			} catch (error) {
				uni.hideLoading();
				console.error('创建订单失败', error);
				console.error('错误详情:', error.response || error.message);
				
				let errorMsg = '创建订单失败';
				if (error.response && error.response.data && error.response.data.message) {
					errorMsg = error.response.data.message;
				} else if (error.message) {
					errorMsg = error.message;
				}
				
				uni.showToast({
					title: errorMsg,
					icon: 'none',
					duration: 2000
				});
			}
		},
		
		goBack() {
			uni.navigateBack();
		}
	}
};
</script>

<style lang="scss" scoped>
.order-confirm {
	min-height: 100vh;
	background: #F5F5F5;
	padding-bottom: 70px;
	
	.header {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		height: 44px;
		background: #fff;
		display: flex;
		align-items: center;
		padding: 0 16px;
		z-index: 100;
		border-bottom: 1px solid #EEEEEE;
		
		.back-btn {
			width: 44px;
			height: 44px;
			display: flex;
			align-items: center;
			justify-content: center;
		}
		
		.title {
			flex: 1;
			text-align: center;
			font-size: 17px;
			font-weight: 500;
			color: #333;
			margin-left: -44px;
		}
	}
	
	.content {
		margin-top: 44px;
		
		.scenic-info {
			background: #fff;
			padding: 16px;
			display: flex;
			align-items: flex-start;
			gap: 12px;
			margin-bottom: 12px;
			
			.scenic-icon {
				width: 100px;
				height: 100px;
				border-radius: 8px;
				object-fit: cover;
				flex-shrink: 0;
			}
			
			.scenic-details {
				flex: 1;
				display: flex;
				flex-direction: column;
				justify-content: center;
				gap: 8px;
				
				.scenic-name {
					font-size: 18px;
					font-weight: 600;
					color: #333;
					line-height: 1.4;
				}
				
				.scenic-address {
					font-size: 14px;
					color: #999;
					line-height: 1.4;
				}
			}
		}
		
		.ticket-info {
			background: #fff;
			padding: 16px;
			margin-bottom: 12px;
			
			.info-row {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 12px 0;
				border-bottom: 1px solid #F5F5F5;
				
				&:last-child {
					border-bottom: none;
				}
				
				.label {
					font-size: 15px;
					color: #666;
				}
				
				.value {
					font-size: 15px;
					color: #333;
				}
				
				.counter {
					display: flex;
					align-items: center;
					gap: 16px;
					
					.count {
						font-size: 16px;
						font-weight: 500;
						color: #333;
						min-width: 30px;
						text-align: center;
					}
				}
				
				.price {
					font-size: 16px;
					font-weight: 500;
					color: #FF6B6B;
				}
			}
		}
		
		.coupon-section {
			background: #fff;
			padding: 16px;
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 12px;
			
			.label {
				font-size: 15px;
				color: #666;
			}
			
			.coupon-value {
				display: flex;
				align-items: center;
				gap: 8px;
				font-size: 15px;
				color: #FF6B6B;
				
				.placeholder {
					color: #999;
				}
			}
		}
		
		.payment-section {
			background: #fff;
			padding: 16px;
			margin-bottom: 12px;
			
			.section-title {
				font-size: 15px;
				color: #666;
				margin-bottom: 12px;
			}
			
			.payment-methods {
				display: flex;
				flex-direction: column;
				gap: 12px;
				
				.payment-item {
					display: flex;
					align-items: center;
					padding: 12px;
					border: 1px solid #EEEEEE;
					border-radius: 8px;
					cursor: pointer;
					transition: all 0.3s;
					
					&.selected {
						border-color: #1890FF;
						background: #F0F8FF;
					}
					
					.payment-icon {
						width: 48px;
						height: 48px;
						margin-right: 16px;
						display: flex;
						align-items: center;
						justify-content: center;
					}
					
					.payment-name {
						flex: 1;
						font-size: 15px;
						color: #333;
					}
				}
			}
		}
		
		.total-section {
			background: #fff;
			padding: 16px;
			
			.total-row {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 8px 0;
				
				.label {
					font-size: 14px;
					color: #666;
				}
				
				.price {
					font-size: 14px;
					color: #333;
				}
				
				.discount {
					font-size: 14px;
					color: #FF6B6B;
				}
				
				&.final {
					padding-top: 16px;
					border-top: 1px solid #F5F5F5;
					
					.label {
						font-size: 16px;
						font-weight: 500;
						color: #333;
					}
					
					.total-price {
						font-size: 20px;
						font-weight: 600;
						color: #FF6B6B;
					}
				}
			}
		}
	}
	
	.footer {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 60px;
		background: #fff;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 16px;
		box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
		
		.price-info {
			display: flex;
			align-items: baseline;
			gap: 8px;
			
			.label {
				font-size: 14px;
				color: #666;
			}
			
			.total {
				font-size: 24px;
				font-weight: 600;
				color: #FF6B6B;
			}
		}
		
		.pay-btn {
			padding: 12px 40px;
			background: #FF6B6B;
			border-radius: 25px;
			
			text {
				font-size: 16px;
				font-weight: 500;
				color: #fff;
			}
		}
	}
}
</style>
